package com.mt.channel.service.model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.github.pagehelper.PageHelper;
import com.mt.channel.entity.ChannelAccountEntity;
import com.mt.channel.entity.ChannelCourseEntity;
import com.mt.channel.entity.ChannelCoursePriceEntity;
import com.mt.channel.entity.ChannelEntity;
import com.mt.channel.mapper.*;
import com.mt.common.PagerInfo;
import com.mt.common.ServiceResult;
import com.mt.common.util.ConvertUtil;

@Component
public class ChannelServiceModel {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChannelServiceModel.class);

    @Autowired
    private ChannelEntityMapper channelEntityMapper;

    @Autowired
    private ChannelAccountEntityMapper channelAccountEntityMapper;

    @Autowired
    private ChannelCourseEntityMapper channelCourseEntityMapper;

    @Autowired
    private ChannelCoursePriceEntityMapper channelCoursePriceEntityMapper;

    @Autowired
    private ChannelCustomerEntityMapper channelCustomerEntityMapper;

    public ServiceResult<List<ChannelEntity>> selectList(Map<String, Object> params, PagerInfo<?> pagerInfo) {
        Assert.notNull(this.channelEntityMapper, "Property 'channelEntityMapper' is required.");
        ServiceResult<List<ChannelEntity>> result = new ServiceResult<List<ChannelEntity>>();
        try {
            if (pagerInfo != null) {
                PageHelper.startPage(pagerInfo.getPageIndex(), pagerInfo.getPageSize());
            }
            List<ChannelEntity> ChannelEntityResult = this.channelEntityMapper.selectList(params);
            result.setResult(ChannelEntityResult);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[ChannelServiceModel][selectList]：query selectList occur exception", e);
        }
        return result;
    }

    public ServiceResult<ChannelEntity> selectInfo(Map<String, Object> params) {
        Assert.notNull(this.channelEntityMapper, "Property 'channelEntityMapper' is required.");
        ServiceResult<ChannelEntity> result = new ServiceResult<ChannelEntity>();
        boolean channelBoolean = false;
        Map<String, Object> relateParams = null;
        try {
            ChannelEntity channelEntity = this.channelEntityMapper.selectByPrimaryKey(params);
            if (params.containsKey("channelSelectAllByChannelIdBoolean")) {
                channelBoolean = ConvertUtil.toBool(params.get("channelSelectAllByChannelIdBoolean"), false);
            }
            if (channelEntity != null && channelBoolean) {
                relateParams = new HashMap<String, Object>();
                relateParams.put("channelId", channelEntity.getChannelId());
                Integer channelCourseCount = channelCourseEntityMapper.selectChannelCourseCounts(relateParams);
                channelEntity.setChannelCourseCounts(channelCourseCount);
                Integer channelCustomerCount = channelCustomerEntityMapper.selectChannelCustomerCounts(params);
                channelEntity.setChannelCustomerCounts(channelCustomerCount);
            }
            result.setResult(channelEntity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[ChannelServiceModel][selectInfo]：query selectInfo occur exception", e);
        }
        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000,
        rollbackFor = Exception.class)
    public ServiceResult<Integer> insert(ChannelEntity channelEntity) {
        Assert.notNull(this.channelEntityMapper, "Property 'channelEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        int id = 0;
        try {
            int save = this.channelEntityMapper.insert(channelEntity);
            if (save > 0) {
                id = channelEntity.getChannelId();
                if (channelEntity.getChannelAccountEntity() != null) {
                    ChannelAccountEntity channelAccountEntity = channelEntity.getChannelAccountEntity();
                    channelAccountEntity.setChannelId(id);
                    channelAccountEntityMapper.insert(channelAccountEntity);
                }
            }
            result.setResult(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[ChannelServiceModel][insert]：query insert occur exception", e);
            throw new RuntimeException(e.getMessage());
        }
        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000,
        rollbackFor = Exception.class)
    public ServiceResult<Integer> updateRelate(ChannelEntity channelEntity) {
        Assert.notNull(this.channelEntityMapper, "Property 'channelEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        int id = 0;
        try {
            int save = this.channelEntityMapper.updateByPrimaryKeySelective(channelEntity);
            if (save > 0) {
                id = channelEntity.getChannelId();
                List<ChannelCourseEntity> channelCourseList = channelEntity.getChannelCourseList();
                if (channelCourseList != null && channelCourseList.size() > 0) {
                    // 编辑渠道商关联课程，由于渠道商可关联多个课程数据，所以修改时候批量全部删除后批量添加
                    channelCourseEntityMapper.deleteByPrimaryKey(channelEntity.getChannelId());
                    channelCoursePriceEntityMapper.deleteByPrimaryKey(channelEntity.getChannelId());
                    channelCourseEntityMapper.insertList(channelCourseList);
                    for (int i = 0; i < channelCourseList.size(); i++) {
                        ChannelCourseEntity channelCourseEntity = channelCourseList.get(i);
                        List<ChannelCoursePriceEntity> channelCoursePriceList =
                            channelCourseEntity.getChannelCoursePriceList();
                        if (channelCoursePriceList != null && channelCoursePriceList.size() > 0) {
                            channelCoursePriceEntityMapper.insertList(channelCoursePriceList);
                        }
                    }
                }
            }
            result.setResult(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[ChannelServiceModel][updateByPrimaryKeySelective]:query update occur exception", e);
            throw new RuntimeException(e.getMessage());
        }
        return result;
    }

    public ServiceResult<Integer> updateByPrimaryKeySelective(ChannelEntity channelEntity) {
        Assert.notNull(this.channelEntityMapper, "Property 'channelEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        int id = 0;
        try {
            int save = this.channelEntityMapper.updateByPrimaryKeySelective(channelEntity);
            if (save > 0) {
                id = channelEntity.getChannelId();
            }
            result.setResult(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[ChannelServiceModel][updateByPrimaryKeySelective]:query update occur exception", e);
        }
        return result;
    }

    public ServiceResult<Integer> deleteByPrimaryKey(Integer channelId) {
        Assert.notNull(this.channelEntityMapper, "Property 'channelEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        int save = 0;
        try {
            save = this.channelEntityMapper.updateByPrimaryKey(channelId);
            result.setResult(save);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[ChannelServiceModel][updateByPrimaryKeySelective]:query update occur exception", e);
        }
        return result;
    }
}
